<template>
  <div class="uav-model-layer"></div>
</template>

<script setup>
import * as Cesium from "cesium";
import { watch, defineExpose, ref, onBeforeUnmount, onMounted } from "vue";
import UavModelLayerCLass from "./UavModelLayerClass.js";
import { useUavModelLayerStore } from "../../store/uavModelLayer.js";
import GridCell from "./GridCell_v2.3.js";

// ==================== 常量配置 ====================
const UAV_CONFIG = [
  {
    name: "无人机26号",
    file: "25FH5603-XHJ.json",
    planFile: "25FH5603-XHJ.json",
    snCode: "UAV-0261",
    img: "/img/uav_2_1.svg",
    color: 1,
  },
  {
    name: "无人机26号",
    file: "0000754126-A.json",
    planFile: "0000754126-A.json",
    snCode: "UAV-0262",
    img: "/img/uav_2_1.svg",
    color: 1,
  },
  {
    name: "无人机26号",
    file: "AD134123.json",
    planFile: "AD134123.json",
    snCode: "UAV-0263",
    img: "/img/uav_2_1.svg",
    color: 1,
  },
  // 可以在这里添加更多无人机配置
];

const ANIMATION_INTERVAL = 1000; // 动画间隔时间（毫秒）
const CAMERA_HEIGHT_OFFSET = 500; // 相机高度偏移

// ==================== 全局状态管理 ====================
let uavModelLayer = null;
const uavModeStore = useUavModelLayerStore();
const intervalId = ref(null);

// 数据存储
const uavLayerMap = new Map();
const gridCells = new Map();
const uavData = ref({
  trajectories: {},      // 实际轨迹数据
  planTrajectories: {},  // 计划轨迹数据
  indices: {},           // 当前轨迹索引
  lastPositions: {},     // 最后位置记录
  completedFirstLoop: new Map(), // 完成第一轮标记
});

// ==================== 核心功能函数 ====================

/**
 * 初始化无人机图层
 */
function initialize (Viewer) {
  uavModelLayer = new UavModelLayerCLass(Viewer, uavLayerMap);
}

/**
 * 加载单个无人机的轨迹数据
 */
async function loadUavTrajectoryData (uavConfig) {
  try {
    const [actualData, planData] = await Promise.all([
      fetch(`/json1/${uavConfig.file}`).then(res => res.json()),
      fetch(`/json1/${uavConfig.planFile}`).then(res => res.json())
    ]);

    // 存储数据
    uavData.value.trajectories[uavConfig.file] = actualData;
    uavData.value.planTrajectories[uavConfig.planFile] = planData;
    uavData.value.indices[uavConfig.file] = 0;
    uavData.value.lastPositions[uavConfig.file] = actualData[0] || [];

    return { actualData, planData };
  } catch (error) {
    console.error(`加载无人机 ${uavConfig.name} 轨迹数据失败:`, error);
    return { actualData: [], planData: [] };
  }
}

/**
 * 加载所有无人机轨迹数据
 */
async function loadAllUavData () {
  console.log("开始加载所有无人机轨迹数据...");

  const loadPromises = UAV_CONFIG.map(loadUavTrajectoryData);
  await Promise.all(loadPromises);

  console.log("所有无人机轨迹数据加载完成");
}

/**
 * 创建单个无人机及其网格
 */
function createUavAndGrid (uavConfig, index) {
  const actualTrajectory = uavData.value.trajectories[uavConfig.file];
  const planTrajectory = uavData.value.planTrajectories[uavConfig.planFile];

  // 验证数据
  if (!actualTrajectory?.length) {
    console.warn(`无人机 ${uavConfig.name} 的实际轨迹数据为空`);
    return false;
  }

  if (!planTrajectory?.length) {
    console.warn(`无人机 ${uavConfig.name} 的计划轨迹数据为空`);
    return false;
  }

  const firstPosition = actualTrajectory[0];

  // 创建无人机
  if (!uavModelLayer.hasUav(uavConfig.snCode)) {
    uavModelLayer.addUav({
      snCode: uavConfig.snCode,
      initPostion: firstPosition,
      ownerType: uavConfig.color,
      productCode: uavConfig.name,
      speedNum: 10 + index,
      height: firstPosition[2],
      img: uavConfig.img,
    });
  }

  // 创建网格
  if (!gridCells.has(uavConfig.snCode)) {
    console.log(`创建 ${uavConfig.name} 的网格，起始位置:`, firstPosition);

    const gridCell = new GridCell(uavModelLayer.viewer, firstPosition);
    gridCells.set(uavConfig.snCode, gridCell);

    // 绘制计划轨迹（绿色方格）
    console.log(`绘制 ${uavConfig.name} 的计划轨迹，共 ${planTrajectory.length} 个点`);
    // console.log(planTrajectory, "planTrajectory");

    gridCell.loadGridDataJson(planTrajectory, 'Green');
    // console.log(`${uavConfig.name} 的绿色计划轨迹绘制完成`);
  }

  return true;
}

/**
 * 创建所有无人机并开始运动
 */
function createAllUavs () {
  console.log("开始创建所有无人机...");

  let successCount = 0;
  UAV_CONFIG.forEach((uavConfig, index) => {
    if (createUavAndGrid(uavConfig, index)) {
      successCount++;
    }
  });

  if (successCount > 0) {
    console.log(`成功创建 ${successCount} 个无人机，开始动画`);
    intervalId.value = setInterval(moveAllUavs, ANIMATION_INTERVAL);
  } else {
    console.error("没有成功创建任何无人机");
  }
}

/**
 * 移动单个无人机
 */
function moveSingleUav (uavConfig) {
  const { file, snCode } = uavConfig;
  const trajectory = uavData.value.trajectories[file];
  const currentIndex = uavData.value.indices[file];

  if (!trajectory?.length || currentIndex >= trajectory.length) {
    return;
  }

  const position = trajectory[currentIndex];

  // 更新无人机位置
  uavModelLayer.moveUav({ snCode, position });

  // 更新无人机信息
  uavModelLayer.updateUavInfo({
    snCode,
    position,
    ownerType: uavConfig.color,
    flightStatus: 0,
    productCode: uavConfig.name,
    speedNum: 10 + currentIndex,
    height: position[2],
    img: uavConfig.img,
  });

  // 添加轨迹点标记
  // addTrajectoryMarker(position, currentIndex);

  // 更新网格颜色
  updateGridColor(snCode, position, currentIndex);

  // 更新索引和状态
  updateUavState(uavConfig, currentIndex, trajectory.length);
}

/**
 * 添加轨迹点标记
 */
function addTrajectoryMarker (position, index) {
  uavModelLayer.viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(position[0], position[1], position[2]),
    point: {
      color: Cesium.Color.RED,
      pixelSize: 10,
    },
    label: {
      text: `${index}`,
      font: "14px sans-serif",
      fillColor: Cesium.Color.WHITE,
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      outlineColor: Cesium.Color.BLACK,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -10),
    },
  });
}

/**
 * 更新网格颜色
 */
function updateGridColor (snCode, position, currentIndex) {
  const gridCell = gridCells.get(snCode);
  if (gridCell) {
    console.log(`将第 ${currentIndex} 个位置的方格改为白色:`, position);
    gridCell.changeColor({
      position,
      color: 'White',
      isGridColor: true,
      mode: 1,
    });
  }
}

/**
 * 更新无人机状态
 */
function updateUavState (uavConfig, currentIndex, trajectoryLength) {
  const { file, snCode } = uavConfig;

  // 记录当前位置
  uavData.value.lastPositions[file] = uavData.value.trajectories[file][currentIndex];

  // 判断是否到达轨迹末尾
  const isLastPosition = currentIndex >= trajectoryLength - 1;

  // 更新索引，循环播放轨迹
  uavData.value.indices[file] = isLastPosition ? 0 : currentIndex + 1;

  // 标记完成第一遍轨迹
  if (isLastPosition) {
    uavData.value.completedFirstLoop.set(snCode, true);
  }
}

/**
 * 移动所有无人机
 */
function moveAllUavs () {
  UAV_CONFIG.forEach(moveSingleUav);
}

/**
 * 停止所有无人机的运动
 */
function stopAllUavs () {
  if (intervalId.value) {
    clearInterval(intervalId.value);
    intervalId.value = null;
    console.log("已停止所有无人机运动");
  }
}

/**
 * 飞向第一个无人机位置
 */
function flyToFirstUav () {
  const firstUavConfig = UAV_CONFIG[0];
  const firstTrajectory = uavData.value.trajectories[firstUavConfig.file];

  if (firstTrajectory?.length) {
    const firstPosition = firstTrajectory[0];
    uavModelLayer.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        firstPosition[0],
        firstPosition[1],
        firstPosition[2] + CAMERA_HEIGHT_OFFSET
      ),
      duration: 2,
      complete: createAllUavs,
    });
  } else {
    console.warn("没有找到第一个无人机的轨迹数据");
    createAllUavs(); // 即使没有轨迹数据也尝试创建
  }
}

/**
 * 设置无人机 - 主要入口函数
 */
async function setupUavs () {
  try {
    await loadAllUavData();
    flyToFirstUav();
  } catch (error) {
    console.error("设置无人机失败:", error);
  }
}

/**
 * 切换无人机显示模式（图标/3D模型）
 */
function switchUavModel () {
  if (!uavModelLayer || uavLayerMap.size === 0) {
    console.warn("无人机图层未初始化或没有无人机");
    return;
  }

  // 获取第一个无人机来检查当前显示状态
  const firstUavItem = uavLayerMap.values().next().value;
  if (!firstUavItem) return;

  const isShowingModel = firstUavItem.uavIcon.model.color.getValue().alpha > 0;

  // 切换所有无人机的显示模式
  uavLayerMap.forEach((uavItem) => {
    if (isShowingModel) {
      // 切换回图标
      uavItem.uavIcon.model.color = new Cesium.Color(1.0, 1.0, 1.0, 0.0);
      uavItem.uavIcon.billboard.show = true;
    } else {
      // 切换到3D模型
      uavItem.uavIcon.model.color = new Cesium.Color(1.0, 1.0, 1.0, 1.0);
      uavItem.uavIcon.billboard.show = false;
    }
  });

  console.log(`已切换到${isShowingModel ? '图标' : '3D模型'}显示模式`);
}

// ==================== 生命周期管理 ====================

onMounted(async () => {
  console.log("UavModelLayer 组件已挂载，开始设置无人机");
  await setupUavs();
});

onBeforeUnmount(() => {
  console.log("UavModelLayer 组件即将卸载，清理资源");
  stopAllUavs();

  // 清理网格资源
  gridCells.forEach((gridCell) => {
    if (gridCell.destroy) {
      gridCell.destroy();
    }
  });
  gridCells.clear();
});

// ==================== 响应式监听 ====================

// 可以根据需要启用这个监听器
// watch(() => uavModeStore.isActive, async (isActive) => {
//   if (isActive) {
//     await setupUavs()
//   } else {
//     stopAllUavs()
//   }
// })

// ==================== 组件导出 ====================

defineExpose({
  initialize,
  switchUavModel,
});
</script>

<style scoped lang="scss"></style>
